package com.ssm.juc.theadpool.task;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 订单任务管理器
 */
@Slf4j
public class OrderTaskManager {


    private static volatile OrderTaskManager instance;

    private ThreadPoolExecutor orderThreadPool;

    public static OrderTaskManager getInstance() {
        if (instance == null) {
            synchronized (OrderTaskManager.class) {
                if (instance == null) {
                    instance = new OrderTaskManager();
                }
            }
        }
        return instance;
    }

    private OrderTaskManager() {
        int nThreads = Runtime.getRuntime().availableProcessors() * 2;
        int workQueueCapacity = 2000;
        LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(workQueueCapacity);
        //创建线程池
        orderThreadPool = new ThreadPoolExecutor(nThreads, nThreads,
                2, TimeUnit.SECONDS,
                workQueue, new TTheadFactory(), new TRejectedExecutionHandler());
        //预热: 初始化所有的线程
        orderThreadPool.prestartAllCoreThreads();
        log.info("orderThreadPool coreSize:{}, maxSize:{}, queueSize:{}.", nThreads, nThreads * 2, workQueueCapacity);
    }

    /**
     * 任务提交
     *
     * @param orderTask 订单任务
     */
    public void submit(OrderTask orderTask) {
        orderThreadPool.submit(orderTask);
    }
}
